package com.heima.search.controller.v1;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchService;
import com.heima.search.service.UserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-20 11:18
 */
@RestController
@RequestMapping("/api/v1/article/search")
public class SearchController {

    @Autowired
    private SearchService searchService;
    @Autowired
    private UserSearchService userSearchService;

    @PostMapping("/search")
    public ResponseResult search(
            @RequestBody UserSearchDto dto) {

        if (dto.getPageSize() <= 0 || dto.getPageSize() >= 50) {
            dto.setPageSize(10);
        }
        //1.搜索
        List<Map> result = searchService.search(dto);

//        if(dto.getIsSearch() != null && dto.getIsSearch() == 1){
            //2.用户搜索记录保存
            if (StringUtils.isNotBlank(dto.getSearchWords())) {
                Integer id = AppThreadLocalUtil.getUser().getId();
                userSearchService.save(dto.getSearchWords(),id);
            }
//        }

        return ResponseResult.okResult(result);
    }
}
